<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络云设备故障管理系统</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <style>
        :root {
            --primary-color: #4285f4;
            --success-color: #34a853;
            --warning-color: #fbbc05;
            --danger-color: #ea4335;
            --info-color: #6ba4f8;
            --dark-color: #333;
            --light-color: #f8f9fa;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: linear-gradient(135deg, var(--primary-color), #3461b3);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            text-align: left;
        }
        
        h1 {
            margin: 0;
            font-size: 2em;
            text-align: left;
        }
        
        .dashboard {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        
        .card {
            background: white;
            border-radius: 8px;
            padding: 10px 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            text-align: center;
            transition: transform 0.3s ease;
            min-width: 120px;
            flex: 1;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card h3 {
            margin-top: 0;
            color: #333;
            font-size: 0.9em;
        }
        
        .card .value {
            font-size: 1.5em;
            font-weight: bold;
            margin: 5px 0;
        }
        
        .card.total { border-top: 4px solid var(--primary-color); }
        .card.resolved { border-top: 4px solid var(--success-color); }
        .card.unresolved { border-top: 4px solid var(--warning-color); }
        
        /* 新增统计卡片容器 */
        .stats-container {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        
        .stats-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 15px;
            flex: 1;
            min-width: 250px;
        }
        
        .stats-item {
            text-align: center;
            flex: 1;
        }
        
        .stats-item h3 {
            margin: 0 0 5px 0;
            font-size: 0.9em;
            color: #666;
        }
        
        .stats-item .value {
            font-size: 1.8em;
            font-weight: bold;
            margin: 0;
        }
        
        .total .value { color: var(--primary-color); }
        .resolved .value { color: var(--success-color); }
        .unresolved .value { color: var(--warning-color); }
        
        .section-title {
            color: #333;
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 8px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .controls {
            background: white;
            border-radius: 8px;
            padding: 15px 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 25px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        
        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
        }
        
        /* 高级搜索样式 */
        .advanced-search-container {
            background: white;
            border-radius: 8px;
            padding: 15px 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 25px;
        }
        
        .selected-filters {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .filter-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .filter-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 10px;
        }
        
        .filter-tag {
            background: #e9ecef;
            border-radius: 12px;
            padding: 4px 10px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .filter-tag .remove-tag {
            cursor: pointer;
            color: #6c757d;
            font-weight: bold;
        }
        
        .filter-tag.empty-filter {
            background: transparent;
            padding: 4px 0;
        }
        
        .filter-actions-inline {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .filter-row {
            margin-bottom: 15px;
        }
        
        .filter-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .filter-options {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .filter-btn {
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 13px;
            cursor: pointer;
        }
        
        .filter-btn:hover {
            background: #e9ecef;
        }
        
        .filter-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .dropdown {
            position: relative;
        }
        
        .dropdown-toggle {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .caret {
            font-size: 10px;
        }
        
        .dropdown-menu {
            position: absolute;
            top: 100%;
            left: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 10px;
            min-width: 200px;
            z-index: 1000;
            margin-top: 5px;
        }
        
        .dropdown-items {
            max-height: 200px;
            overflow-y: auto;
            margin-bottom: 10px;
        }
        
        .dropdown-item {
            padding: 6px 10px;
            cursor: pointer;
            border-radius: 4px;
        }
        
        .dropdown-item:hover {
            background: #f8f9fa;
        }
        
        .dropdown-item.selected {
            background: #e3f2fd;
        }
        
        .form-control {
            width: 100%;
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 13px;
        }
        
        .filter-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 25px;
            overflow-x: auto; /* 水平滚动 */
            overflow-y: hidden; /* 垂直滚动由分页控制 */
            max-height: none;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1400px;
            table-layout: fixed;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        /* 选中行高亮显示 */
        tr.selected {
            background-color: #e3f2fd !important;
        }
        
        th, td {
            padding: 6px 8px;
            text-align: left;
            border-bottom: 1px solid #eee;
            white-space: normal;
            word-wrap: break-word;
            line-height: 1.3;
            font-size: 12px;
            vertical-align: top; /* 顶部对齐 */
        }
        
        /* 特定列的宽度控制 */
        th:nth-child(1), td:nth-child(1) { /* 厂家 */
            white-space: nowrap;
            width: 50px;
            min-width: 50px;
        }
        
        th:nth-child(2), td:nth-child(2) { /* 设备名称 */
            white-space: normal;
            word-wrap: break-word;
            width: 20ch;
            min-width: 20ch;
        }
        
        th:nth-child(3), td:nth-child(3) { /* 故障时间 */
            white-space: nowrap;
            width: 100px;
            min-width: 100px;
        }
        
        th:nth-child(4), td:nth-child(4) { /* 告警名称 */
            white-space: normal;
            word-wrap: break-word;
            width: 20ch;
            min-width: 20ch;
        }
        
        th:nth-child(5), td:nth-child(5) { /* 告警级别 */
            white-space: nowrap;
            width: 60px;
            min-width: 60px;
            text-align: center;
        }
        
        th:nth-child(6), td:nth-child(6) { /* 设备序列号 */
            white-space: normal;
            word-wrap: break-word;
            width: 20ch;
            min-width: 20ch;
        }
        
        th:nth-child(7), td:nth-child(7) { /* 处理结果 */
            white-space: normal;
            word-wrap: break-word;
            width: 10ch;
            min-width: 10ch;
        }
        
        th:nth-child(8), td:nth-child(8) { /* 恢复时间 */
            white-space: nowrap;
            width: 140px;
            min-width: 140px;
        }
        
        th:nth-child(9), td:nth-child(9) { /* 备注1 */
            white-space: normal;
            word-wrap: break-word;
            width: 20ch;
            min-width: 20ch;
        }
        
        th:nth-child(10), td:nth-child(10) { /* 备注2 */
            white-space: normal;
            word-wrap: break-word;
            width: 20ch;
            min-width: 20ch;
        }
        
        th:nth-child(11), td:nth-child(11) { /* 状态 */
            white-space: nowrap;
            width: 60px;
            min-width: 60px;
            text-align: center;
        }
        
        th:nth-child(12), td:nth-child(12) { /* 操作 */
            white-space: nowrap;
            width: 120px;
            min-width: 120px;
            text-align: center;
        }
        
        th {
            background-color: var(--primary-color);
            color: white;
            font-weight: 600;
            position: sticky;
            top: 0;
            text-align: left;
        }
        
        /* 移除列调整大小的手柄 */
        .resizer {
            display: none;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .status-resolved {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-unresolved {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .action-btn {
            padding: 3px 6px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 3px;
            display: inline-block;
            min-width: 70px;
        }
        
        .action-btn.edit {
            background-color: var(--info-color);
            color: white;
        }
        
        .action-btn.delete {
            background-color: var(--danger-color);
            color: white;
        }
        
        .btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .btn:hover {
            background: #3367d6;
        }
        
        .btn.success { background: var(--success-color); }
        .btn.success:hover { background: #2d9247; }
        
        .btn.warning { background: var(--warning-color); }
        .btn.warning:hover { background: #e6ac00; }
        
        .btn.danger { background: var(--danger-color); }
        .btn.danger:hover { background: #d33a2c; }
        
        .btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
        }
        
        .search-box {
            flex: 1;
            min-width: 200px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .charts-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .chart-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .chart-card h3 {
            margin-top: 0;
            color: #333;
            text-align: center;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background: white;
            border-radius: 8px;
            padding: 20px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .close {
            font-size: 24px;
            cursor: pointer;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 15px;
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }
        
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: white;
            border-radius: 8px;
            padding: 15px 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-top: 15px;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .pagination-info {
            font-size: 14px;
            color: #666;
        }
        
        .pagination-controls {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .pagination-btn {
            padding: 6px 12px;
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .pagination-btn:hover:not(:disabled) {
            background: #e9ecef;
        }
        
        .pagination-btn:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        .current-page {
            padding: 6px 12px;
            background: var(--primary-color);
            color: white;
            border-radius: 4px;
            font-weight: bold;
        }
        
        .pagination-size {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
        }
        
        .pagination-size select {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .dashboard {
                flex-direction: column;
            }
            
            .card {
                padding: 15px;
            }
            
            .controls {
                flex-direction: column;
                align-items: stretch;
            }
            
            .search-box {
                min-width: 100%;
            }
            
            th, td {
                padding: 8px 10px;
                font-size: 14px;
            }
            
            .charts-container {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>网络云设备故障管理系统</h1>
        </header>

        <!-- 修改统计卡片布局 -->
        <div class="stats-container">
            <div class="stats-card">
                <div class="stats-item total">
                    <h3>总故障数</h3>
                    <div class="value" id="totalCount">0</div>
                </div>
                <div class="stats-item resolved">
                    <h3>已解决</h3>
                    <div class="value" id="resolvedCount">0</div>
                </div>
                <div class="stats-item unresolved">
                    <h3>未解决</h3>
                    <div class="value" id="unresolvedCount">0</div>
                </div>
            </div>
        </div>

        <div class="charts-container">
            <div class="chart-card">
                <h3>最近一周故障数量趋势</h3>
                <div style="position: relative; height: 300px; width: 100%;">
                    <canvas id="trendChart" style="display: block; width: 100%; height: 100%;"></canvas>
                </div>
            </div>
            <div class="chart-card">
                <h3>厂家故障统计</h3>
                <div style="position: relative; height: 300px; width: 100%;">
                    <canvas id="manufacturerChart" style="display: block; width: 100%; height: 100%;"></canvas>
                </div>
            </div>
        </div>

        <div>
            <div class="section-title">
                <h2>故障明细</h2>
            </div>
            
            <!-- 高级搜索区域 -->
            <div class="advanced-search-container">
                <!-- 已选择的条件 -->
                <div class="selected-filters" id="selectedFiltersContainer">
                    <div class="filter-header">
                        <span>您已选择：</span>
                    </div>
                    <div class="filter-tags" id="selectedFilters"></div>
                    <!-- 将清空和过滤按钮移到这里 -->
                    <div class="filter-actions-inline" style="margin-top: 10px;">
                        <button class="btn btn-sm" id="clearAllFilters">清空</button>
                        <button class="btn btn-sm success" id="applyFilters">过滤</button>
                    </div>
                </div>
                
                <!-- 故障时间筛选 -->
                <div class="filter-row">
                    <div class="filter-item">
                        <label>故障时间：</label>
                        <div class="filter-options">
                            <button class="filter-btn" data-filter="time" data-value="1">最近1天</button>
                            <button class="filter-btn" data-filter="time" data-value="3">最近3天</button>
                            <button class="filter-btn" data-filter="time" data-value="7">最近7天</button>
                            <button class="filter-btn" data-filter="time" data-value="30">最近30天</button>
                            <button class="filter-btn" id="customDateBtn">自定义日期</button>
                        </div>
                    </div>
                </div>
                
                <!-- 自定义日期弹窗 -->
                <div id="customDateModal" class="modal" style="display: none;">
                    <div class="modal-content" style="max-width: 400px;">
                        <div class="modal-header">
                            <h3>自定义日期</h3>
                            <span class="close" id="closeCustomDateModal">&times;</span>
                        </div>
                        <div class="form-group">
                            <label for="startDate">开始日期：</label>
                            <input type="date" id="startDate" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="endDate">结束日期：</label>
                            <input type="date" id="endDate" class="form-control">
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn" id="cancelCustomDate">取消</button>
                            <button type="button" class="btn success" id="confirmCustomDate">确认</button>
                        </div>
                    </div>
                </div>
                
                <!-- 更多选项筛选 -->
                <div class="filter-row">
                    <div class="filter-item">
                        <label>更多选项：</label>
                        <div class="filter-options">
                            <div class="dropdown">
                                <button class="filter-btn dropdown-toggle" id="factoryFilterBtn">
                                    厂家 <span class="caret">▼</span>
                                </button>
                                <div class="dropdown-menu" id="factoryDropdown" style="display: none;">
                                    <input type="text" class="form-control" placeholder="输入厂家名称" id="factorySearchInput">
                                    <div class="form-actions">
                                        <button type="button" class="btn" id="cancelFactoryFilter">取消</button>
                                        <button type="button" class="btn success" id="confirmFactoryFilter">确定</button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="dropdown">
                                <button class="filter-btn dropdown-toggle" id="hostFilterBtn">
                                    设备名称 <span class="caret">▼</span>
                                </button>
                                <div class="dropdown-menu" id="hostDropdown" style="display: none;">
                                    <input type="text" class="form-control" placeholder="输入设备名称" id="hostSearchInput">
                                    <div class="form-actions">
                                        <button type="button" class="btn" id="cancelHostFilter">取消</button>
                                        <button type="button" class="btn success" id="confirmHostFilter">确定</button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="dropdown">
                                <button class="filter-btn dropdown-toggle" id="alarmFilterBtn">
                                    告警名称 <span class="caret">▼</span>
                                </button>
                                <div class="dropdown-menu" id="alarmDropdown" style="display: none;">
                                    <input type="text" class="form-control" placeholder="输入告警名称" id="alarmSearchInput">
                                    <div class="form-actions">
                                        <button type="button" class="btn" id="cancelAlarmFilter">取消</button>
                                        <button type="button" class="btn success" id="confirmAlarmFilter">确定</button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="dropdown">
                                <button class="filter-btn dropdown-toggle" id="statusFilterBtn">
                                    状态 <span class="caret">▼</span>
                                </button>
                                <div class="dropdown-menu" id="statusDropdown" style="display: none;">
                                    <div class="dropdown-items">
                                        <div class="dropdown-item" data-value="resolved">已处理</div>
                                        <div class="dropdown-item" data-value="unresolved">未处理</div>
                                    </div>
                                    <div class="form-actions">
                                        <button type="button" class="btn" id="cancelStatusFilter">取消</button>
                                        <button type="button" class="btn success" id="confirmStatusFilter">确定</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="table-container" id="tableContainer">
                <table>
                    <thead>
                        <tr>
                            <th>厂家</th>
                            <th>设备名称</th>
                            <th>故障时间</th>
                            <th>告警名称</th>
                            <th>告警级别</th>
                            <th>设备序列号</th>
                            <th>处理结果</th>
                            <th>恢复时间</th>
                            <th>备注1</th>
                            <th>备注2</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="faultTableBody">
                        <tr>
                            <td colspan="12" style="text-align: center;">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- 添加分页控件 -->
            <div class="pagination-container">
                <div class="pagination-info">
                    <span id="pageInfo">第 1 页，共 1 页</span>
                    <span id="totalRecordsInfo" style="margin-left: 20px;">共 0 条记录</span>
                </div>
                <div class="pagination-controls">
                    <button id="firstPageBtn" class="pagination-btn" disabled>首页</button>
                    <button id="prevPageBtn" class="pagination-btn" disabled>上一页</button>
                    <div id="pageNumbers" style="display: flex; align-items: center; gap: 5px;"></div>
                    <button id="nextPageBtn" class="pagination-btn" disabled>下一页</button>
                    <button id="lastPageBtn" class="pagination-btn" disabled>末页</button>
                </div>
                <div class="pagination-size">
                    <label for="pageSizeSelect">每页显示：</label>
                    <select id="pageSizeSelect">
                        <option value="6" selected>6条</option>
                        <option value="10">10条</option>
                        <option value="20">20条</option>
                        <option value="50">50条</option>
                    </select>
                </div>
            </div>
        </div>
        
        <div class="controls">
            <button id="addFaultBtn" class="btn"><i>+</i> 添加故障</button>
            <button id="refreshBtn" class="btn">刷新数据</button>
            <button id="exportBtn" class="btn success">导出数据</button>
            <button id="importBtn" class="btn warning">导入数据</button>
            <!-- SQL操作按钮 -->
            <button id="bulkActionBtn" class="btn danger">请输入SQL语句执行操作（支持TRUNCATE、SELECT、UPDATE、DELETE）</button>
        </div>
    </div>

    <!-- 添加/编辑故障模态框 ，为添加故障记录模态框关闭按钮添加ID-->
    <div id="faultModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">添加故障记录</h2>
                <span class="close" id="closeFaultModal">&times;</span> 
            </div>

            <form id="faultForm">
                <input type="hidden" id="faultId" name="faultId">
                <div class="form-group">
                    <label for="factoryName">厂家 *</label>
                    <input type="text" id="factoryName" name="factoryName" required>
                </div>
                <div class="form-group">
                    <label for="hostName">设备名称 *</label>
                    <input type="text" id="hostName" name="hostName" required>
                </div>
                <div class="form-group">
                    <label for="faultTime">故障时间 *</label>
                    <input type="datetime-local" id="faultTime" name="faultTime" required>
                    <small>提示：可以粘贴时间格式如 2025-09-24 10:30:00 或 2025/1/28 0:56:46</small>
                </div>
                <div class="form-group">
                    <label for="alarmName">告警名称 *</label>
                    <input type="text" id="alarmName" name="alarmName" required>
                </div>
                <div class="form-group">
                    <label for="level">告警级别</label>
                    <select id="level" name="level">
                        <option value="">请选择</option>
                        <option value="低">低</option>
                        <option value="中">中</option>
                        <option value="高">高</option>
                        <option value="紧急">紧急</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="deviceSn">设备序列号</label>
                    <input type="text" id="deviceSn" name="deviceSn">
                </div>
                <div class="form-group">
                    <label for="resolution">处理结果</label>
                    <input type="text" id="resolution" name="resolution">
                </div>
                <div class="form-group">
                    <label for="recoveryTime">恢复时间</label>
                    <input type="datetime-local" id="recoveryTime" name="recoveryTime">
                    <small>提示：可以粘贴时间格式如 2025-09-24 11:30:00 或 2025/1/28 0:56:46</small>
                </div>
                <div class="form-group">
                    <label for="note1">备注1</label>
                    <textarea id="note1" name="note1" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label for="note2">备注2</label>
                    <textarea id="note2" name="note2" rows="2"></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" id="cancelBtn">取消</button>
                    <button type="submit" class="btn success">保存</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 导入数据模态框 -->
    <div id="importModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>导入故障记录</h2>
                <span class="close" id="closeImportModal">&times;</span>
            </div>
            <div class="info-message">
                <p><strong>注意：</strong>系统将自动检查并跳过重复记录（基于厂家、设备名称、故障时间和告警名称）。</p>
            </div>
            <form id="importForm">
                <div class="form-group">
                    <label for="importFile">选择文件 *</label>
                    <input type="file" id="importFile" accept=".csv,.xlsx,.xls" required>
                </div>
                <div class="form-group" id="csvOptions">
                    <label>
                        <input type="checkbox" id="hasHeader" checked> 文件包含标题行（仅CSV）
                    </label>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" id="cancelImportBtn">取消</button>
                    <button type="submit" class="btn warning">导入</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 批量操作模态框 -->
    <div id="bulkActionModal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h2>SQL操作(目前仅有一个fault_statistics表)</h2>
                <span class="close" id="closeBulkActionModal">&times;</span>
            </div>
            <div style="margin-bottom: 15px;">
                <p>请输入SQL语句执行操作（支持truncate、SELECT、UPDATE、DELETE）</p>
            </div>
            <div class="form-group">
                <label for="sqlQuery">SQL语句 *</label>
                <textarea id="sqlQuery" rows="6" placeholder="例如：SELECT * FROM fault_statistics WHERE factory_name = '华为'"></textarea>
            </div>
            <div class="form-group">
                <label for="sqlResult">执行结果：</label>
                <textarea id="sqlResult" rows="8" readonly></textarea>
            </div>
            <div class="form-actions">
                <button type="button" class="btn" id="cancelBulkActionBtn">取消</button>
                <button type="button" class="btn warning" id="executeSqlBtn">执行</button>
            </div>
        </div>
    </div>

    <script>
        // API基础URL
        const API_BASE = 'http://localhost:8000/api/v1';
        
        // 图表实例
        let trendChart = null;
        let manufacturerChart = null;
        
        // 高级搜索相关变量
        let selectedFilters = {
            time: null,
            customDate: { start: null, end: null },
            factories: [],
            hosts: [],
            alarms: [],
            status: null
        };
        
        // DOM元素
        const totalCountEl = document.getElementById('totalCount');
        const resolvedCountEl = document.getElementById('resolvedCount');
        const unresolvedCountEl = document.getElementById('unresolvedCount');
        const faultTableBodyEl = document.getElementById('faultTableBody');
        const refreshBtn = document.getElementById('refreshBtn');
        const addFaultBtn = document.getElementById('addFaultBtn');
        const exportBtn = document.getElementById('exportBtn');
        const importBtn = document.getElementById('importBtn');
        const faultModal = document.getElementById('faultModal');
        const importModal = document.getElementById('importModal');
        const modalTitle = document.getElementById('modalTitle');
        const faultForm = document.getElementById('faultForm');
        const importForm = document.getElementById('importForm');
        const closeBtn = document.getElementById('closeFaultModal');
        const closeImportModal = document.getElementById('closeImportModal');
        const cancelBtn = document.getElementById('cancelBtn');
        const cancelImportBtn = document.getElementById('cancelImportBtn');
        const tableContainer = document.getElementById('tableContainer');
        // 批量操作元素
        const bulkActionBtn = document.getElementById('bulkActionBtn');
        const bulkActionModal = document.getElementById('bulkActionModal');
        const closeBulkActionModal = document.getElementById('closeBulkActionModal');
        const cancelBulkActionBtn = document.getElementById('cancelBulkActionBtn');
        const executeSqlBtn = document.getElementById('executeSqlBtn');
        const sqlQueryInput = document.getElementById('sqlQuery');
        const sqlResultTextarea = document.getElementById('sqlResult');
        // 分页相关元素
        const firstPageBtn = document.getElementById('firstPageBtn');
        const prevPageBtn = document.getElementById('prevPageBtn');
        const nextPageBtn = document.getElementById('nextPageBtn');
        const lastPageBtn = document.getElementById('lastPageBtn');
        const currentPageSpan = document.getElementById('currentPage');
        const pageInfoSpan = document.getElementById('pageInfo');
        const pageSizeSelect = document.getElementById('pageSizeSelect');
        
        // 高级搜索DOM元素
        const selectedFiltersContainer = document.getElementById('selectedFiltersContainer');
        const selectedFiltersEl = document.getElementById('selectedFilters');
        const clearAllFiltersBtn = document.getElementById('clearAllFilters');
        const customDateBtn = document.getElementById('customDateBtn');
        const customDateModal = document.getElementById('customDateModal');
        const closeCustomDateModal = document.getElementById('closeCustomDateModal');
        const cancelCustomDateBtn = document.getElementById('cancelCustomDate');
        const confirmCustomDateBtn = document.getElementById('confirmCustomDate');
        const startDateInput = document.getElementById('startDate');
        const endDateInput = document.getElementById('endDate');
        const applyFiltersBtn = document.getElementById('applyFilters');
        
        // 下拉菜单元素
        const factoryFilterBtn = document.getElementById('factoryFilterBtn');
        const factoryDropdown = document.getElementById('factoryDropdown');
        const factorySearchInput = document.getElementById('factorySearchInput');
        const cancelFactoryFilterBtn = document.getElementById('cancelFactoryFilter');
        const confirmFactoryFilterBtn = document.getElementById('confirmFactoryFilter');
        
        const hostFilterBtn = document.getElementById('hostFilterBtn');
        const hostDropdown = document.getElementById('hostDropdown');
        const hostSearchInput = document.getElementById('hostSearchInput');
        const cancelHostFilterBtn = document.getElementById('cancelHostFilter');
        const confirmHostFilterBtn = document.getElementById('confirmHostFilter');
        
        const alarmFilterBtn = document.getElementById('alarmFilterBtn');
        const alarmDropdown = document.getElementById('alarmDropdown');
        const alarmSearchInput = document.getElementById('alarmSearchInput');
        const cancelAlarmFilterBtn = document.getElementById('cancelAlarmFilter');
        const confirmAlarmFilterBtn = document.getElementById('confirmAlarmFilter');
        
        const statusFilterBtn = document.getElementById('statusFilterBtn');
        const statusDropdown = document.getElementById('statusDropdown');
        const cancelStatusFilterBtn = document.getElementById('cancelStatusFilter');
        const confirmStatusFilterBtn = document.getElementById('confirmStatusFilter');
        
        // 分页状态
        let currentPage = 1;
        let pageSize = 6; // 默认每页6条记录
        let totalRecords = 0;
        let totalPages = 1;
        let isAdvancedSearch = false; // 是否使用高级搜索
        
        // 初始化事件监听器
        function initEventListeners() {
            // 为每个按钮添加点击事件监听器
            if (refreshBtn) {
                refreshBtn.addEventListener('click', refreshAllData);
            }
            if (addFaultBtn) {
                addFaultBtn.addEventListener('click', openAddFaultModal);
            }
            if (exportBtn) {
                exportBtn.addEventListener('click', exportFaults);
            }
            if (importBtn) {
                importBtn.addEventListener('click', openImportModal);
            }
            if (faultForm) {
                faultForm.addEventListener('submit', saveFault);
            }
            if (importForm) {
                importForm.addEventListener('submit', importFaults);
            }
            if (closeBtn) {
                closeBtn.addEventListener('click', closeFaultModal);
            }
            if (closeImportModal) {
                closeImportModal.addEventListener('click', closeImportModalFunc);
            }
            if (cancelBtn) {
                cancelBtn.addEventListener('click', closeFaultModal);
            }
            if (cancelImportBtn) {
                cancelImportBtn.addEventListener('click', closeImportModalFunc);
            }
            
            // SQL操作事件监听器
            if (bulkActionBtn) {
                bulkActionBtn.addEventListener('click', openBulkActionModal);
            }
            if (closeBulkActionModal) {
                closeBulkActionModal.addEventListener('click', closeBulkActionModalFunc);
            }
            if (cancelBulkActionBtn) {
                cancelBulkActionBtn.addEventListener('click', closeBulkActionModalFunc);
            }
            if (executeSqlBtn) {
                executeSqlBtn.addEventListener('click', executeSqlQuery);
            }
            
            // 分页事件监听器
            if (firstPageBtn) {
                firstPageBtn.addEventListener('click', goToFirstPage);
            }
            if (prevPageBtn) {
                prevPageBtn.addEventListener('click', goToPrevPage);
            }
            if (nextPageBtn) {
                nextPageBtn.addEventListener('click', goToNextPage);
            }
            if (lastPageBtn) {
                lastPageBtn.addEventListener('click', goToLastPage);
            }
            if (pageSizeSelect) {
                pageSizeSelect.addEventListener('change', changePageSize);
            }
            
            // 高级搜索事件监听器
            initAdvancedSearchListeners();
            
            // 添加文件选择变化监听器
            const importFileElement = document.getElementById('importFile');
            if (importFileElement) {
                importFileElement.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        const fileName = file.name.toLowerCase();
                        const csvOptions = document.getElementById('csvOptions');
                        // 如果是CSV文件，显示CSV选项；否则隐藏
                        if (csvOptions) {
                            if (fileName.endsWith('.csv')) {
                                csvOptions.style.display = 'block';
                            } else {
                                csvOptions.style.display = 'none';
                            }
                        }
                    }
                });
            }
            
            // 为故障时间和恢复时间字段添加粘贴事件监听器
            const faultTimeElement = document.getElementById('faultTime');
            const recoveryTimeElement = document.getElementById('recoveryTime');
            if (faultTimeElement) faultTimeElement.addEventListener('paste', handleDateTimePaste);
            if (recoveryTimeElement) recoveryTimeElement.addEventListener('paste', handleDateTimePaste);
            
            window.addEventListener('click', (event) => {
                if (event.target === faultModal) {
                    closeFaultModal();
                }
                if (event.target === importModal) {
                    closeImportModalFunc();
                }
                if (event.target === bulkActionModal) {
                    closeBulkActionModalFunc();
                }
                if (event.target === customDateModal) {
                    closeCustomDateModalFunc();
                }
                // 点击其他地方关闭下拉菜单
                if (factoryFilterBtn && factoryDropdown && 
                    !factoryFilterBtn.contains(event.target) && !factoryDropdown.contains(event.target)) {
                    factoryDropdown.style.display = 'none';
                }
                if (hostFilterBtn && hostDropdown && 
                    !hostFilterBtn.contains(event.target) && !hostDropdown.contains(event.target)) {
                    hostDropdown.style.display = 'none';
                }
                if (alarmFilterBtn && alarmDropdown && 
                    !alarmFilterBtn.contains(event.target) && !alarmDropdown.contains(event.target)) {
                    alarmDropdown.style.display = 'none';
                }
                if (statusFilterBtn && statusDropdown && 
                    !statusFilterBtn.contains(event.target) && !statusDropdown.contains(event.target)) {
                    statusDropdown.style.display = 'none';
                }
            });
        }
        
        // 初始化高级搜索事件监听器
        function initAdvancedSearchListeners() {
            // 清空所有筛选条件
            if (clearAllFiltersBtn) clearAllFiltersBtn.addEventListener('click', clearAllFilters);
            
            // 故障时间筛选
            const timeFilterButtons = document.querySelectorAll('[data-filter="time"]');
            timeFilterButtons.forEach(btn => {
                btn.addEventListener('click', selectTimeFilter);
            });
            
            // 自定义日期
            if (customDateBtn) customDateBtn.addEventListener('click', openCustomDateModal);
            if (closeCustomDateModal) closeCustomDateModal.addEventListener('click', closeCustomDateModalFunc);
            if (cancelCustomDateBtn) cancelCustomDateBtn.addEventListener('click', closeCustomDateModalFunc);
            if (confirmCustomDateBtn) confirmCustomDateBtn.addEventListener('click', confirmCustomDate);
            
            // 厂家筛选
            if (factoryFilterBtn) {
                factoryFilterBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    if (factoryDropdown) toggleDropdown(factoryDropdown);
                });
            }
            if (cancelFactoryFilterBtn) cancelFactoryFilterBtn.addEventListener('click', function() {
                if (factoryDropdown) factoryDropdown.style.display = 'none';
            });
            if (confirmFactoryFilterBtn) confirmFactoryFilterBtn.addEventListener('click', confirmFactoryFilter);
            
            // 设备名称筛选
            if (hostFilterBtn) {
                hostFilterBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    if (hostDropdown) toggleDropdown(hostDropdown);
                });
            }
            if (cancelHostFilterBtn) cancelHostFilterBtn.addEventListener('click', function() {
                if (hostDropdown) hostDropdown.style.display = 'none';
            });
            if (confirmHostFilterBtn) confirmHostFilterBtn.addEventListener('click', confirmHostFilter);
            
            // 告警名称筛选
            if (alarmFilterBtn) {
                alarmFilterBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    if (alarmDropdown) toggleDropdown(alarmDropdown);
                });
            }
            if (cancelAlarmFilterBtn) cancelAlarmFilterBtn.addEventListener('click', function() {
                if (alarmDropdown) alarmDropdown.style.display = 'none';
            });
            if (confirmAlarmFilterBtn) confirmAlarmFilterBtn.addEventListener('click', confirmAlarmFilter);
            
            // 状态筛选
            if (statusFilterBtn) {
                statusFilterBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    // 打开状态筛选下拉菜单时，保持之前选中的状态
                    if (statusDropdown) {
                        statusDropdown.querySelectorAll('.dropdown-item').forEach(item => {
                            item.classList.remove('selected');
                        });
                        
                        // 根据已选中的状态设置选中状态
                        if (selectedFilters.status) {
                            const selectedItem = statusDropdown.querySelector(`.dropdown-item[data-value="${selectedFilters.status}"]`);
                            if (selectedItem) {
                                selectedItem.classList.add('selected');
                            }
                        }
                        toggleDropdown(statusDropdown);
                    }
                });
            }
            
            if (statusDropdown) {
                statusDropdown.querySelectorAll('.dropdown-item').forEach(item => {
                    item.addEventListener('click', function() {
                        this.classList.toggle('selected');
                    });
                });
            }
            
            if (cancelStatusFilterBtn) cancelStatusFilterBtn.addEventListener('click', function() {
                if (statusDropdown) statusDropdown.style.display = 'none';
            });
            if (confirmStatusFilterBtn) confirmStatusFilterBtn.addEventListener('click', confirmStatusFilter);
            
            // 应用筛选按钮
            if (applyFiltersBtn) applyFiltersBtn.addEventListener('click', applyFilters);
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 确保所有DOM元素都已加载
            setTimeout(function() {
                initEventListeners();
                refreshAllData();
            }, 100);
        });
        
        // 切换下拉菜单显示状态
        function toggleDropdown(dropdown) {
            const isVisible = dropdown.style.display === 'block';
            // 隐藏所有下拉菜单
            document.querySelectorAll('.dropdown-menu').forEach(menu => {
                menu.style.display = 'none';
            });
            // 切换当前菜单
            dropdown.style.display = isVisible ? 'none' : 'block';
        }
        
        // 选择时间筛选条件
        function selectTimeFilter(event) {
            const days = event.target.getAttribute('data-value');
            selectedFilters.time = days;
            updateSelectedFiltersDisplay();
            document.querySelectorAll('[data-filter="time"]').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');
        }
        
        // 打开自定义日期弹窗
        function openCustomDateModal() {
            customDateModal.style.display = 'block';
            // 设置默认日期为今天
            const today = new Date();
            const startDate = new Date(today);
            startDate.setDate(today.getDate() - 7);
            
            startDateInput.value = startDate.toISOString().split('T')[0];
            endDateInput.value = today.toISOString().split('T')[0];
        }
        
        // 关闭自定义日期弹窗
        function closeCustomDateModalFunc() {
            customDateModal.style.display = 'none';
        }
        
        // 确认自定义日期
        function confirmCustomDate() {
            const startDate = startDateInput.value;
            const endDate = endDateInput.value;
            
            if (startDate && endDate) {
                selectedFilters.customDate = { start: startDate, end: endDate };
                selectedFilters.time = 'custom';
                updateSelectedFiltersDisplay();
                closeCustomDateModalFunc();
            } else {
                alert('请选择完整的日期范围');
            }
        }
        
        
        // 确认厂家筛选
        function confirmFactoryFilter() {
            const inputValue = factorySearchInput.value.trim();
            if (inputValue) {
                // 直接将输入的值添加到厂家筛选条件中
                if (!selectedFilters.factories.includes(inputValue)) {
                    selectedFilters.factories.push(inputValue);
                }
                // 清空输入框
                factorySearchInput.value = '';
            }
            updateSelectedFiltersDisplay();
            factoryDropdown.style.display = 'none';
        }
        
        // 确认设备名称筛选
        function confirmHostFilter() {
            const inputValue = hostSearchInput.value.trim();
            if (inputValue) {
                // 直接将输入的值添加到设备名称筛选条件中
                if (!selectedFilters.hosts.includes(inputValue)) {
                    selectedFilters.hosts.push(inputValue);
                }
                // 清空输入框
                hostSearchInput.value = '';
            }
            updateSelectedFiltersDisplay();
            hostDropdown.style.display = 'none';
        }
        
        // 确认告警名称筛选
        function confirmAlarmFilter() {
            const inputValue = alarmSearchInput.value.trim();
            if (inputValue) {
                // 直接将输入的值添加到告警名称筛选条件中
                if (!selectedFilters.alarms.includes(inputValue)) {
                    selectedFilters.alarms.push(inputValue);
                }
                // 清空输入框
                alarmSearchInput.value = '';
            }
            updateSelectedFiltersDisplay();
            alarmDropdown.style.display = 'none';
        }
        

        
        // 确认状态筛选
        function confirmStatusFilter() {
            const selectedItems = Array.from(statusDropdown.querySelectorAll('.dropdown-item.selected'))
                .map(item => item.getAttribute('data-value'));
            selectedFilters.status = selectedItems.length > 0 ? selectedItems[0] : null;
            updateSelectedFiltersDisplay();
            statusDropdown.style.display = 'none';
        }
        
        // 更新已选择筛选条件显示
        function updateSelectedFiltersDisplay() {
            selectedFiltersEl.innerHTML = '';
            let hasFilters = false;
            
            // 时间筛选
            if (selectedFilters.time) {
                hasFilters = true;
                let filterText = '';
                if (selectedFilters.time === 'custom') {
                    filterText = `自定义日期: ${selectedFilters.customDate.start} 至 ${selectedFilters.customDate.end}`;
                } else {
                    filterText = `最近${selectedFilters.time}天`;
                }
                
                const tag = createFilterTag(filterText, 'time');
                selectedFiltersEl.appendChild(tag);
            }
            
            // 厂家筛选
            if (selectedFilters.factories.length > 0) {
                hasFilters = true;
                selectedFilters.factories.forEach(factory => {
                    const tag = createFilterTag(`厂家: ${factory}`, 'factory', factory);
                    selectedFiltersEl.appendChild(tag);
                });
            }
            
            // 设备名称筛选
            if (selectedFilters.hosts.length > 0) {
                hasFilters = true;
                selectedFilters.hosts.forEach(host => {
                    const tag = createFilterTag(`设备: ${host}`, 'host', host);
                    selectedFiltersEl.appendChild(tag);
                });
            }
            
            // 告警名称筛选
            if (selectedFilters.alarms.length > 0) {
                hasFilters = true;
                selectedFilters.alarms.forEach(alarm => {
                    const tag = createFilterTag(`告警: ${alarm}`, 'alarm', alarm);
                    selectedFiltersEl.appendChild(tag);
                });
            }
            
            // 状态筛选
            if (selectedFilters.status) {
                hasFilters = true;
                const statusText = selectedFilters.status === 'resolved' ? '已处理' : '未处理';
                const tag = createFilterTag(`状态: ${statusText}`, 'status');
                selectedFiltersEl.appendChild(tag);
            }
            
            // 始终显示"您已选择"区域，但如果没有筛选条件则显示提示信息
            if (!hasFilters) {
                const emptyMessage = document.createElement('div');
                emptyMessage.className = 'filter-tag empty-filter';
                emptyMessage.textContent = '暂无筛选条件';
                emptyMessage.style.color = '#999';
                emptyMessage.style.fontStyle = 'italic';
                selectedFiltersEl.appendChild(emptyMessage);
            }
            
            // 移除了selectedFiltersContainer.style.display的设置，确保始终显示
        }
        
        // 创建筛选标签
        function createFilterTag(text, type, value = null) {
            const tag = document.createElement('div');
            tag.className = 'filter-tag';
            tag.innerHTML = `
                ${text}
                <span class="remove-tag" data-type="${type}" data-value="${value || ''}">&times;</span>
            `;
            
            // 添加删除事件
            tag.querySelector('.remove-tag').addEventListener('click', function() {
                removeFilter(type, value);
            });
            
            return tag;
        }
        
        // 打开添加故障模态框
        function openAddFaultModal() {
            // 设置模态框标题为"添加故障记录"
            modalTitle.textContent = '添加故障记录';
            // 重置表单内容，清空所有输入字段
            faultForm.reset();
            // 显示添加故障的模态框
            faultModal.style.display = 'block';
        }
        
        // 获取故障数据
        async function fetchFaults() {
            if (isAdvancedSearch) {
                await fetchFaultsWithFilters();
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/faults?page=${currentPage}&size=${pageSize}`);
                if (response.ok) {
                    const data = await response.json();
                    totalRecords = data.totalRecords;
                    totalPages = data.totalPages;
                    renderFaultTable(data.faults);
                    updatePaginationInfo();
                } else {
                    faultTableBodyEl.innerHTML = '<tr><td colspan="12" style="text-align: center; color: red;">数据加载失败，请刷新页面重试</td></tr>';
                }
            } catch (error) {
                faultTableBodyEl.innerHTML = '<tr><td colspan="12" style="text-align: center; color: red;">数据加载异常，请检查网络连接</td></tr>';
            }
        }
        
        // 刷新所有数据
        async function refreshAllData() {
            try {
                // 重置为普通搜索模式
                isAdvancedSearch = false;
                currentPage = 1;
                
                // 清空筛选条件
                clearAllFilters();
                
                // 刷新数据
                await Promise.all([
                    fetchTotalCounts(),
                    fetchFaults(),
                    fetchTrendData(),
                    fetchManufacturerData()
                ]);
            } catch (error) {
                console.error("刷新数据时发生错误:", error);
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 确保所有DOM元素都已加载
            setTimeout(function() {
                initEventListeners();
                refreshAllData();
            }, 100);
        });
        
        // 删除筛选条件
        function removeFilter(type, value) {
            switch (type) {
                case 'time':
                    selectedFilters.time = null;
                    selectedFilters.customDate = { start: null, end: null };
                    // 移除时间按钮的激活状态
                    document.querySelectorAll('[data-filter="time"]').forEach(btn => {
                        btn.classList.remove('active');
                    });
                    break;
                case 'factory':
                    selectedFilters.factories = selectedFilters.factories.filter(f => f !== value);
                    break;
                case 'host':
                    selectedFilters.hosts = selectedFilters.hosts.filter(h => h !== value);
                    break;
                case 'alarm':
                    selectedFilters.alarms = selectedFilters.alarms.filter(a => a !== value);
                    break;
                case 'status':
                    selectedFilters.status = null;
                    break;
            }
            updateSelectedFiltersDisplay();
            fetchFaults();
        }
        
        // 清空所有筛选条件
        function clearAllFilters() {
            selectedFilters = {
                time: null,
                customDate: { start: null, end: null },
                factories: [],
                hosts: [],
                alarms: [],
                status: null
            };
            
            // 清除时间按钮激活状态
            document.querySelectorAll('[data-filter="time"]').forEach(btn => {
                btn.classList.remove('active');
            });
            
            updateSelectedFiltersDisplay();
            isAdvancedSearch = false;
            currentPage = 1;
        }
        
        // 应用筛选条件
        async function applyFilters() {
            isAdvancedSearch = true;
            currentPage = 1;
            await fetchFaultsWithFilters();
        }
        
        // 使用筛选条件获取故障数据
        async function fetchFaultsWithFilters() {
            try {
                const searchRequest = {
                    page: currentPage,
                    size: pageSize,
                    factory_names: selectedFilters.factories.length > 0 ? selectedFilters.factories : null,
                    host_names: selectedFilters.hosts.length > 0 ? selectedFilters.hosts : null,
                    alarm_names: selectedFilters.alarms.length > 0 ? selectedFilters.alarms : null,
                    start_date: selectedFilters.customDate.start,
                    end_date: selectedFilters.customDate.end,
                    status: selectedFilters.status
                };
                
                // 如果是预设时间范围，计算日期
                if (selectedFilters.time && selectedFilters.time !== 'custom') {
                    const days = parseInt(selectedFilters.time);
                    const endDate = new Date();
                    const startDate = new Date();
                    startDate.setDate(endDate.getDate() - days + 1);
                    
                    searchRequest.start_date = startDate.toISOString().split('T')[0];
                    searchRequest.end_date = endDate.toISOString().split('T')[0];
                }
                
                const response = await fetch(`${API_BASE}/faults/advanced-search`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(searchRequest)
                });
                
                if (response.ok) {
                    const data = await response.json();
                    totalRecords = data.totalRecords;
                    totalPages = data.totalPages;
                    renderFaultTable(data.faults);
                    updatePaginationInfo();
                } else {
                    if (faultTableBodyEl) {
                        faultTableBodyEl.innerHTML = '<tr><td colspan="12" style="text-align: center; color: red;">数据加载失败，请重试</td></tr>';
                    }
                }
            } catch (error) {
                if (faultTableBodyEl) {
                    faultTableBodyEl.innerHTML = '<tr><td colspan="12" style="text-align: center; color: red;">数据加载异常，请检查网络连接</td></tr>';
                }
            }
        }
        
        // 渲染故障表格
        function renderFaultTable(faults) {
            if (!faultTableBodyEl) return;
            
            if (faults.length === 0) {
                faultTableBodyEl.innerHTML = '<tr><td colspan="12" style="text-align: center;">暂无数据</td></tr>';
                return;
            }
            
            faultTableBodyEl.innerHTML = faults.map(fault => {
                // 处理时间字段
                let faultTime = '-';
                if (fault.fault_time && fault.fault_time !== 'nan') {
                    try {
                        faultTime = new Date(fault.fault_time).toLocaleString('zh-CN');
                    } catch (e) {
                        faultTime = fault.fault_time;
                    }
                }
                
                let recoveryTime = '-';
                if (fault.recovery_time && fault.recovery_time !== 'nan') {
                    try {
                        recoveryTime = new Date(fault.recovery_time).toLocaleString('zh-CN');
                    } catch (e) {
                        recoveryTime = fault.recovery_time;
                    }
                }
                
                const statusClass = (fault.resolution && fault.resolution !== 'nan' && fault.resolution.trim() !== '') ? 'status-resolved' : 'status-unresolved';
                const statusText = (fault.resolution && fault.resolution !== 'nan' && fault.resolution.trim() !== '') ? '已处理' : '未处理';
                
                // 处理其他字段，将'nan'替换为'-'
                const factoryName = (fault.factory_name && fault.factory_name !== 'nan') ? fault.factory_name : '-';
                const hostName = (fault.host_name && fault.host_name !== 'nan') ? fault.host_name : '-';
                const alarmName = (fault.alarm_name && fault.alarm_name !== 'nan') ? fault.alarm_name : '-';
                const level = (fault.level && fault.level !== 'nan') ? fault.level : '-';
                const deviceSn = (fault.device_sn && fault.device_sn !== 'nan') ? fault.device_sn : '-';
                const resolution = (fault.resolution && fault.resolution !== 'nan') ? fault.resolution : '-';
                const note1 = (fault.note1 && fault.note1 !== 'nan') ? fault.note1 : '-';
                const note2 = (fault.note2 && fault.note2 !== 'nan') ? fault.note2 : '-';
                
                return `
                    <tr data-id="${fault.id}">
                        <td>${factoryName}</td>
                        <td>${hostName}</td>
                        <td>${faultTime}</td>
                        <td>${alarmName}</td>
                        <td style="text-align: center;">${level}</td>
                        <td>${deviceSn}</td>
                        <td>${resolution}</td>
                        <td>${recoveryTime}</td>
                        <td>${note1}</td>
                        <td>${note2}</td>
                        <td style="text-align: center;"><span class="status-badge ${statusClass}" style="font-size: 11px; padding: 2px 6px;">${statusText}</span></td>
                        <td>
                            <button class="action-btn edit" onclick="editFault(${fault.id})">编辑</button>
                            <button class="action-btn delete" onclick="deleteFault(${fault.id})">删除</button>
                        </td>
                    </tr>
                `;
            }).join('');
            
            // 为表格行添加点击事件监听器
            addRowClickListeners();
        }
        
        // 更新分页信息
        function updatePaginationInfo() {
            // 确保所有分页元素都存在
            if (!pageInfoSpan || !document.getElementById('totalRecordsInfo')) return;
            
            // 修正页数显示逻辑：即使没有记录也显示至少1页
            const displayTotalPages = totalPages > 0 ? totalPages : 1;
            pageInfoSpan.textContent = `第 ${currentPage} 页，共 ${displayTotalPages} 页`;
            document.getElementById('totalRecordsInfo').textContent = `共 ${totalRecords} 条记录`;
            
            // 更新按钮状态
            if (firstPageBtn) firstPageBtn.disabled = currentPage === 1;
            if (prevPageBtn) prevPageBtn.disabled = currentPage === 1;
            if (nextPageBtn) nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
            if (lastPageBtn) lastPageBtn.disabled = currentPage === totalPages || totalPages === 0;
            
            // 更新页码数字选项
            updatePageNumbers();
        }
        
        // 更新页码数字选项
        function updatePageNumbers() {
            const pageNumbersContainer = document.getElementById('pageNumbers');
            if (!pageNumbersContainer) return;
            
            pageNumbersContainer.innerHTML = '';
            
            // 如果没有记录，显示第1页
            if (totalRecords === 0) {
                const pageBtn = document.createElement('button');
                pageBtn.className = 'pagination-btn current-page';
                pageBtn.textContent = '1';
                pageBtn.disabled = true;
                pageNumbersContainer.appendChild(pageBtn);
                return;
            }
            
            // 最多显示7个页码按钮（当前页+前后各3个）
            let startPage, endPage;
            if (totalPages <= 7) {
                // 如果总页数小于等于7页，显示所有页码
                startPage = 1;
                endPage = totalPages;
            } else {
                // 如果总页数大于7页，显示部分页码
                if (currentPage <= 4) {
                    // 当前页在前4页内，显示前7页
                    startPage = 1;
                    endPage = 7;
                } else if (currentPage + 3 >= totalPages) {
                    // 当前页在后4页内，显示后7页
                    startPage = totalPages - 6;
                    endPage = totalPages;
                } else {
                    // 当前页在中间，显示当前页前后各3页
                    startPage = currentPage - 3;
                    endPage = currentPage + 3;
                }
            }
            
            // 添加页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.className = 'pagination-btn';
                pageBtn.textContent = i;
                if (i === currentPage) {
                    pageBtn.classList.add('current-page');
                    pageBtn.disabled = true;
                } else {
                    pageBtn.addEventListener('click', () => {
                        goToPage(i);
                    });
                }
                pageNumbersContainer.appendChild(pageBtn);
            }
        }
        
        // 跳转到指定页
        function goToPage(page) {
            if (page >= 1 && page <= totalPages && page !== currentPage) {
                currentPage = page;
                fetchFaults();
            }
        }
        
        // 跳转到第一页
        function goToFirstPage() {
            if (currentPage !== 1) {
                currentPage = 1;
                fetchFaults();
            }
        }
        
        // 跳转到上一页
        function goToPrevPage() {
            if (currentPage > 1) {
                currentPage--;
                fetchFaults();
            }
        }
        
        // 跳转到下一页
        function goToNextPage() {
            if (currentPage < totalPages) {
                currentPage++;
                fetchFaults();
            }
        }
        
        // 跳转到最后一页
        function goToLastPage() {
            if (currentPage !== totalPages) {
                currentPage = totalPages;
                fetchFaults();
            }
        }
        
        // 改变每页显示数量
        function changePageSize() {
            if (pageSizeSelect) {
                pageSize = parseInt(pageSizeSelect.value);
                currentPage = 1; // 重置到第一页
                fetchFaults();
            }
        }
        

        
        // 打开导入故障模态框
        function openImportModal() {
            importModal.style.display = 'block';
        }
        
        // 打开SQL操作模态框
        function openBulkActionModal() {
            bulkActionModal.style.display = 'block';
        }
        
        // 关闭故障模态框
        function closeFaultModal() {
            faultModal.style.display = 'none';
        }
        
        // 关闭导入故障模态框
        function closeImportModalFunc() {
            importModal.style.display = 'none';
        }
        
        // 关闭批量操作模态框
        function closeBulkActionModalFunc() {
            bulkActionModal.style.display = 'none';
        }
        
        // 保存故障记录
        async function saveFault(event) {
            event.preventDefault();
            const formData = new FormData(faultForm);
            const faultData = Object.fromEntries(formData.entries());
            
            // 处理日期时间字段
            if (faultData.faultTime) {
                // 对于datetime-local类型，值已经是正确的格式，只需转换为ISO格式
                const faultDateTime = new Date(faultData.faultTime);
                faultData.fault_time = faultDateTime.toISOString();
            }
            if (faultData.recoveryTime) {
                // 对于datetime-local类型，值已经是正确的格式，只需转换为ISO格式
                const recoveryDateTime = new Date(faultData.recoveryTime);
                faultData.recovery_time = recoveryDateTime.toISOString();
            }
            
            // 处理可选字段 - 修复字段名称匹配问题
            if (!faultData.level) delete faultData.level;
            if (!faultData.deviceSn) delete faultData.deviceSn;
            // 注意：不要删除resolution字段，因为空字符串也需要特殊处理
            if (!faultData.recoveryTime) delete faultData.recovery_time;
            if (!faultData.note1) delete faultData.note1;
            if (!faultData.note2) delete faultData.note2;
            
            // 特别处理resolution字段，确保空字符串也被正确处理
            if (faultData.resolution !== undefined) {
                if (faultData.resolution.trim() === '') {
                    faultData.resolution = null;
                }
            }
            
            // 特别处理其他可能为空字符串的字段
            if (faultData.level !== undefined && faultData.level.trim() === '') {
                delete faultData.level;
            }
            if (faultData.deviceSn !== undefined && faultData.deviceSn.trim() === '') {
                delete faultData.deviceSn;
            }
            if (faultData.note1 !== undefined && faultData.note1.trim() === '') {
                delete faultData.note1;
            }
            if (faultData.note2 !== undefined && faultData.note2.trim() === '') {
                delete faultData.note2;
            }
            
            try {
                let response;
                if (faultData.faultId) {
                    // 更新现有记录
                    response = await fetch(`${API_BASE}/faults/${faultData.faultId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            factory_name: faultData.factoryName,
                            host_name: faultData.hostName,
                            fault_time: faultData.fault_time,
                            alarm_name: faultData.alarmName,
                            level: faultData.level,
                            device_sn: faultData.deviceSn,
                            resolution: (faultData.resolution !== undefined && faultData.resolution !== null && faultData.resolution.trim() === '') ? null : (faultData.resolution || null),
                            recovery_time: faultData.recovery_time,
                            note1: faultData.note1,
                            note2: faultData.note2
                        })
                    });
                } else {
                    // 创建新记录
                    response = await fetch(`${API_BASE}/faults`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            factory_name: faultData.factoryName,
                            host_name: faultData.hostName,
                            fault_time: faultData.fault_time,
                            alarm_name: faultData.alarmName,
                            level: faultData.level,
                            device_sn: faultData.deviceSn,
                            resolution: (faultData.resolution !== undefined && faultData.resolution !== null && faultData.resolution.trim() === '') ? null : (faultData.resolution || null),
                            recovery_time: faultData.recovery_time,
                            note1: faultData.note1,
                            note2: faultData.note2
                        })
                    });
                }
                
                // 检查响应
                if (response.ok) {
                    const responseData = await response.json();
                    closeFaultModal();
                    await refreshAllData();
                    // 添加保存成功的确认弹框
                    alert('故障记录保存成功！');
                } else {
                    const errorText = await response.text();
                    // 显示更详细的错误信息
                    alert(`保存失败: ${response.status} ${response.statusText}\n${errorText}`);
                }
            } catch (error) {
                alert('保存异常，请检查网络连接');
            }
        }
        
        // 导入故障记录
        async function importFaults(event) {
            event.preventDefault();
            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];
            const hasHeader = document.getElementById('hasHeader').checked;
            
            if (!file) {
                alert('请选择一个文件进行导入');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            // 将CSV标题选项传递给后端
            formData.append('hasHeader', hasHeader);
            
            try {
                const response = await fetch(`${API_BASE}/faults/import/excel`, {
                    method: 'POST',
                    body: formData
                });
                
                if (response.ok) {
                    const result = await response.json();
                    // 显示导入结果，包括详细的错误信息
                    let message = `导入完成！${result.message}`;
                    
                    // 如果有详细的错误信息，显示在控制台中
                    if (result.error_details && result.error_details.length > 0) {
                        }
                    
                    // 使用更友好的方式显示结果
                    if (result.error_count > 0) {
                        // 如果有错误，使用confirm对话框让用户选择是否查看详情
                        if (confirm(`${message}\n\n是否要查看详细的错误信息？`)) {
                            // 显示详细的错误信息
                            let errorDetailMessage = "导入失败的详细信息:\n\n";
                            const errorsToShow = result.error_details || [];
                            errorsToShow.forEach(error => {
                                errorDetailMessage += `第${error.row}行: ${error.error}\n  详情: ${error.details}\n\n`;
                            });
                            alert(errorDetailMessage);
                        }
                    } else {
                        // 如果没有错误，直接显示成功消息
                        alert(message);
                    }
                    
                    closeImportModalFunc();
                    await refreshAllData();
                } else {
                    const errorData = await response.json().catch(() => ({}));
                    const errorMsg = errorData.detail || response.statusText || '未知错误';
                    alert(`导入失败: ${errorMsg}\n状态码: ${response.status}`);
                }
            } catch (error) {
                alert(`导入异常，请检查网络连接\n错误信息: ${error.message}`);
            }
        }
        
        // 执行SQL查询
        async function executeSqlQuery() {
            const sqlQuery = sqlQueryInput.value.trim();
            if (!sqlQuery) {
                alert('请输入SQL语句');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/faults/execute-sql`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        query: sqlQuery
                    })
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.type === 'select') {
                        sqlResultTextarea.value = JSON.stringify(result.data, null, 2);
                    } else {
                        sqlResultTextarea.value = `执行成功，影响行数: ${result.row_count}`;
                    }
                } else {
                    const errorText = await response.text();
                                        sqlResultTextarea.value = `执行失败: ${response.statusText}`;
                }
            } catch (error) {
                                sqlResultTextarea.value = '执行异常，请检查网络连接';
            }
        }
        
        // 批量操作
        async function bulkAction(event) {
            event.preventDefault();
            const selectedRows = Array.from(document.querySelectorAll('input[name="rowSelect"]:checked'))
                .map(checkbox => checkbox.value);
            
            if (selectedRows.length === 0) {
                alert('请选择要操作的记录');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/faults/bulk/delete`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ids: selectedRows
                    })
                });
                
                if (response.ok) {
                    closeBulkActionModalFunc();
                    await refreshAllData();
                    alert('批量操作成功！');
                } else {
                    const errorText = await response.text();
                    alert(`批量操作失败: ${response.status} ${response.statusText}\n${errorText}`);
                }
            } catch (error) {
                alert('批量操作异常，请检查网络连接');
            }
        }
        

        
        // 渲染表格
        function renderTable(data) {
            const tableBody = document.getElementById('faultTableBody');
            tableBody.innerHTML = '';
            
            data.forEach(row => {
                const rowElement = document.createElement('tr');
                rowElement.innerHTML = `
                    <td><input type="checkbox" name="rowSelect" value="${row.id}"></td>
                    <td>${row.factory_name}</td>
                    <td>${row.host_name}</td>
                    <td>${row.fault_time}</td>
                    <td>${row.alarm_name}</td>
                    <td>${row.level}</td>
                    <td>${row.device_sn}</td>
                    <td>${row.resolution}</td>
                    <td>${row.recovery_time}</td>
                    <td>${row.note1}</td>
                    <td>${row.note2}</td>
                    <td>
                        <button onclick="editFault(${row.id})">编辑</button>
                        <button onclick="deleteFault(${row.id})">删除</button>
                    </td>
                `;
                tableBody.appendChild(rowElement);
            });
        }
        
        // 编辑故障记录
        async function editFault(id) {
            try {
                const response = await fetch(`${API_BASE}/faults/${id}`);
                if (response.ok) {
                    const fault = await response.json();
                    
                    document.getElementById('factoryName').value = fault.factory_name;
                    document.getElementById('hostName').value = fault.host_name;
                    document.getElementById('faultTime').value = fault.fault_time.replace(' ', 'T').substring(0, 16);
                    document.getElementById('alarmName').value = fault.alarm_name;
                    document.getElementById('level').value = fault.level || '';
                    document.getElementById('deviceSn').value = fault.device_sn || '';
                    // 特别处理resolution字段，确保null值不会被转换为空字符串
                    if (fault.resolution === null || fault.resolution === undefined) {
                        document.getElementById('resolution').value = '';
                    } else {
                        document.getElementById('resolution').value = fault.resolution;
                    }
                    if (fault.recovery_time) {
                        document.getElementById('recoveryTime').value = fault.recovery_time.replace(' ', 'T').substring(0, 16);
                    } else {
                        document.getElementById('recoveryTime').value = '';
                    }
                    document.getElementById('note1').value = fault.note1 || '';
                    document.getElementById('note2').value = fault.note2 || '';
                    document.getElementById('faultId').value = fault.id;
                    
                    // 设置模态框标题为"编辑故障记录"
                    document.getElementById('modalTitle').textContent = '编辑故障记录';
                    openFaultModal();
                } else {
                    alert('获取故障记录失败');
                }
            } catch (error) {
                alert('获取故障记录异常，请检查网络连接');
            }
        }
        
        // 删除故障记录
        async function deleteFault(id) {
            if (confirm('确定要删除这条记录吗？')) {
                try {
                    const response = await fetch(`${API_BASE}/faults/${id}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        await refreshAllData();
                        alert('故障记录删除成功！');
                    } else {
                        const errorText = await response.text();
                        alert(`删除失败: ${response.status} ${response.statusText}\n${errorText}`);
                    }
                } catch (error) {
                    alert('删除异常，请检查网络连接');
                }
            }
        }
        
        // 打开故障记录模态框
        function openFaultModal() {
            document.getElementById('faultModal').style.display = 'block';
        }
        

        
        // 获取总故障数、已解决和未解决的故障数
        async function fetchTotalCounts() {
            try {
                const response = await fetch(`${API_BASE}/faults/stats/summary`);
                if (response.ok) {
                    const counts = await response.json();
                    if (totalCountEl) totalCountEl.textContent = counts.total_count;
                    if (resolvedCountEl) resolvedCountEl.textContent = counts.resolved_count;
                    if (unresolvedCountEl) unresolvedCountEl.textContent = counts.unresolved_count;
                }
            } catch (error) {
                console.error('获取统计数据时发生错误:', error);
            }
        }
        
        // 获取故障趋势数据
        async function fetchTrendData() {
            try {
                const response = await fetch(`${API_BASE}/faults/stats/trend`);
                if (response.ok) {
                    const data = await response.json();
                    // 添加延迟确保DOM完全加载
                    setTimeout(() => {
                        renderTrendChart(data);
                    }, 100);
                }
            } catch (error) {
                console.error('获取趋势数据时发生错误:', error);
            }
        }
        
        // 获取厂家统计信息
        async function fetchManufacturerData() {
            try {
                const response = await fetch(`${API_BASE}/faults/stats/manufacturer`);
                if (response.ok) {
                    const data = await response.json();
                    // 添加延迟确保DOM完全加载
                    setTimeout(() => {
                        renderManufacturerChart(data);
                    }, 100);
                }
            } catch (error) {
                console.error('获取厂家统计数据时发生错误:', error);
            }
        }
        
        // 渲染趋势图表
        function renderTrendChart(data) {
            const ctx = document.getElementById('trendChart');
            if (!ctx) return;
            
            if (trendChart) {
                trendChart.destroy();
            }
            
            // 准备图表数据
            const labels = data.map(item => item.date);
            const counts = data.map(item => item.count);
            
            trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '故障数量',
                        data: counts,
                        borderColor: '#4285f4',
                        backgroundColor: 'rgba(66, 133, 244, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        }
                    }
                }
            });
        }
        
        // 渲染厂家统计图表
        function renderManufacturerChart(data) {
            const ctx = document.getElementById('manufacturerChart');
            if (!ctx) return;
            
            if (manufacturerChart) {
                manufacturerChart.destroy();
            }
            
            // 准备图表数据
            const labels = data.map(item => item.factory_name);
            const counts = data.map(item => item.fault_count);
            
            manufacturerChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '故障数量',
                        data: counts,
                        backgroundColor: '#4285f4',
                        borderColor: '#4285f4',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        }
                    }
                }
            });
        }
        

        

        

        
        // 导出故障记录
        async function exportFaults() {
            try {
                const response = await fetch(`${API_BASE}/faults/export/excel`);
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'faults.xlsx';
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                } else {
                    alert('导出失败，请重试');
                }
            } catch (error) {
                                alert('导出异常，请检查网络连接');
            }
        }
        
        // 为表格行添加点击事件监听器
        function addRowClickListeners() {
            const rows = faultTableBodyEl.querySelectorAll('tr');
            rows.forEach(row => {
                row.addEventListener('click', () => {
                    // 移除其他行的选中状态
                    rows.forEach(r => r.classList.remove('selected'));
                    // 为当前点击的行添加选中状态
                    row.classList.add('selected');
                });
            });
        }
        

        

        
        // 处理日期时间粘贴事件
        function handleDateTimePaste(event) {
            event.preventDefault();
            const pastedData = (event.clipboardData || window.clipboardData).getData('text');
            
            // 尝试解析粘贴的日期时间数据
            const parsedDate = parseDateTime(pastedData);
            if (parsedDate) {
                // 对于datetime-local类型的输入框，我们需要将日期时间转换为正确的格式
                // datetime-local需要格式为 YYYY-MM-DDTHH:mm
                const date = new Date(parsedDate);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                
                // 设置datetime-local输入框的值
                const datetimeLocalValue = `${year}-${month}-${day}T${hours}:${minutes}`;
                event.target.value = datetimeLocalValue;
            } else {
                // 如果无法解析，显示错误提示
                alert('无法解析粘贴的时间格式，请使用标准格式如：2025-09-24 10:30:00 或 2025/1/28 0:56:46');
            }
        }
        
        // 解析日期时间字符串
        function parseDateTime(dateTimeStr) {
            // 移除首尾空格
            dateTimeStr = dateTimeStr.trim();
            
            // 支持的日期时间格式
            const formats = [
                /^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/,  // 2025-9-24 1:30:00 或 2025-09-24 10:30:00
                /^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/,  // 2025/9/24 1:30:00 或 2025/09/24 10:30:00
                /^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})$/,           // 2025-9-24 1:30 或 2025-09-24 10:30
                /^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})$/,         // 2025/9/24 1:30 或 2025/09/24 10:30
                /^(\d{4})-(\d{1,2})-(\d{1,2})$/,                             // 2025-9-24 或 2025-09-24
                /^(\d{4})\/(\d{1,2})\/(\d{1,2})$/                            // 2025/9/24 或 2025/09/24
            ];
            
            for (const format of formats) {
                const match = dateTimeStr.match(format);
                if (match) {
                    // 解构匹配结果，确保月份和日期是两位数格式
                    let [, year, month, day, hour = '00', minute = '00', second = '00'] = match;
                    
                    // 确保月份和日期是两位数格式
                    month = month.padStart(2, '0');
                    day = day.padStart(2, '0');
                    hour = hour.padStart(2, '0');
                    minute = minute.padStart(2, '0');
                    second = second.padStart(2, '0');
                    
                    // 验证日期有效性
                    const date = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`);
                    if (date instanceof Date && !isNaN(date)) {
                        // 转换为datetime-local格式 (YYYY-MM-DDTHH:mm)
                        return `${year}-${month}-${day}T${hour}:${minute}`;
                    }
                }
            }
            
            return null; // 无法解析
        }
        
        // 防抖函数
        /**
         * 防抖函数 - 用于限制函数的执行频率
         * 当函数被频繁调用时，只执行最后一次调用
         * 
         * @param {Function} func - 需要防抖处理的函数
         * @param {number} wait - 延迟执行的毫秒数
         * @returns {Function} 返回一个防抖处理后的函数
         */
        function debounce(func, wait) {
            // 声明一个定时器变量，用于存储setTimeout的返回值
            let timeout;
            
            // 返回一个闭包函数，这个函数会在实际调用时执行
            return function executedFunction(...args) {
                // 定义一个延迟执行的函数
                const later = () => {
                    // 清除之前的定时器，防止之前设置的定时器被执行
                    clearTimeout(timeout);
                    // 使用apply方法调用原函数，确保this指向正确，并传递所有参数
                    func.apply(this, args);
                };
                
                // 在设置新的定时器之前，先清除已存在的定时器
                clearTimeout(timeout);
                // 设置一个新的定时器，延迟执行later函数
                timeout = setTimeout(later, wait);
            };
        }
        
        // 获取最近一周的日期
        function getLastWeekDates() {
            const today = new Date();
            const lastWeek = new Date(today);
            lastWeek.setDate(today.getDate() - 7);
            
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };
            
            return {
                startDate: formatDate(lastWeek),
                endDate: formatDate(today)
            };
        }
        
        
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async () => {
            console.log('页面DOM加载完成');
            try {
                console.log('开始初始化事件监听器...');
                initEventListeners();
                console.log('事件监听器初始化完成');
                
                currentPage = 1; // 初始化当前页
                pageSize = 6; // 设置默认每页显示数量
                console.log('更新筛选显示...');
                updateSelectedFiltersDisplay(); // 初始化时显示"您已选择"区域
                console.log('筛选显示更新完成');
                
                console.log('开始刷新所有数据...');
                await refreshAllData();
                console.log('数据刷新完成');
                
                // 每10分钟自动刷新一次数据
                setInterval(refreshAllData, 600000);
                
                console.log('页面初始化完成');
            } catch (error) {
                console.error("页面初始化时发生错误:", error);
            }
        });
    </script>
</body>
</html>